import { createRouter, createWebHashHistory } from 'vue-router';
import routes from './routes';

const router = createRouter({
  routes,
  history: createWebHashHistory(),
  scrollBehavior() {
    return { top: 0 };
  },
});

// 全局路由守卫
router.beforeEach((to, from, next) => {
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';

  // 如果访问登录页面且已登录，重定向到首页
  if (to.path === '/login' && isLoggedIn) {
    next('/');
    return;
  }

  // 如果页面需要认证且未登录，重定向到登录页
  if (to.meta?.requiresAuth && !isLoggedIn) {
    next('/login');
    return;
  }

  next();
});

export default router;
